<template>
	<div class="app-container flex col-top row-between">
		<div @click="showCate = true" v-if="showCate == false" style="position: fixed;top: 155px;">
			<el-icon class="cursor fs16"><Expand /></el-icon>
		</div>
		<div class="bgWhite radius8" style="width: 280px;padding: 20px;" v-else>
			<div class="flex col-center row-between">
				<span class="main-color">商品类别</span>
				<el-icon class="cursor fs16" @click="showCate = false"><Fold /></el-icon>
			</div>			
			<div class="mt15">
				<el-tree :data="data" node-key="id" default-expand-all :expand-on-click-node="false"
					@node-click="handleNodeClick" :highlight-current="true">
					<template #default="{ node, data }">
						<div class="custom-tree-node flex col-center row-between">
							<span>{{ node.label }}</span>
							<span>
								<el-icon color="#4DACB1" :size="16" @click.stop="() => append(node,data)"
								v-hasPermi="['commodity:classify:add']"
								>
									<Plus />
								</el-icon>
								<el-icon color="#4DACB1" :size="16"  class="mr10 ml10" v-if="node.data.id != -1" type="text" size="mini" @click.stop="() => edit(node,data)"
								v-hasPermi="['commodity:classify:add']"
								>
									<Edit />
								</el-icon>
								<el-icon color="#4DACB1" :size="16" v-if="node.data.id != -1" type="text" size="mini" @click.stop="() => remove(node, data)"
								v-hasPermi="['commodity:classify:remove']"
								>
									<Delete />
								</el-icon>
							</span>
						</div>
					</template>
				</el-tree>
			</div>
		</div>
		<div 
		:class="[{width1: showCate == true},{width2:showCate == false}]"
		>
			<div class="bgWhite radius8">
				<el-form class="p20 flex col-top row-between" style="padding-bottom: 0;" label-width="80px"
					:model="queryParams" ref="queryForm" :inline="true">
					<div>
						<el-form-item label="关键词" prop="keyword">
							<el-input v-model="queryParams.keyword" placeholder="请输入关键词" clearable class="resetInput"
								style="width: 200px" :suffix-icon="Search" @keyup.enter="handleQuery" />
						</el-form-item>
						<el-form-item label="销售渠道" prop="channelType">
							<el-select v-model="queryParams.channelType" placeholder="请选择" size="large"
								style="width: 200px">
								<el-option v-for="dict in bus_channel" :key="dict.value" :label="dict.label"
									:value="dict.value" />
							</el-select>
						</el-form-item>
					</div>
					<el-form-item style="margin-right: 0">
						<div class="flex col-center row-end">
							<el-button class="searchBtn" type="defaultBtn" @click="handleQuery">查询</el-button>
							<el-button class="searchBtn" icon="Refresh" @click="resetQuery">重置</el-button>
						</div>
					</el-form-item>
				</el-form>
			</div>
			<div class="bgWhite radius8 p20 mt25">
				<div class="flex col-center row-between mb20">
					<span class="fb fs16">商品列表</span>
					<div>
						<el-button type="defaultBtn" @click="handleAdd"
						v-hasPermi="['commodity:add']">新增商品
						</el-button>
					</div>
				</div>
				<el-table v-loading="loading" :data="list" style="width: 100%" :header-row-style="{
					background: '#FAFAFA',
					color: '#0C1019',
					height: '54px',
				  }" :cell-style="{ height: '54px' }" @selection-change="handleSelectionChange">
					<el-table-column label="商品图片" align="center" prop="mainImageUrl" width="120">
						<template #default="scope">
							<img :src="scope.row.mainImageUrl ? scope.row.mainImageUrl : defaultImg" class="radius8" style="width: 90px; height: 90px" />
						</template>
					</el-table-column>
					<el-table-column label="商品ID" align="center" prop="commodityCode" width="100"/>
					<el-table-column label="商品名称" align="center" prop="commodityName" width="200"/>
					<el-table-column label="商品分类" align="center" prop="classifyId">
						<template v-slot="scope">
							{{scope.row.classifyName}}
						</template>
					</el-table-column>
					<el-table-column label="折箱价" align="center" prop="boxConversionUnitPrice" width="100">
						<template v-slot="scope">
								￥{{scope.row.boxConversionUnitPrice}}
						</template>
					</el-table-column>
					<el-table-column label="单价" align="center" prop="onlineUnitPrice" width="100" >
						<template v-slot="scope">
							￥{{scope.row.onlineUnitPrice}}
						</template>
					</el-table-column>
					<el-table-column label="箱价" align="center" prop="caseUnitPrice" width="100" >
						<template v-slot="scope">
							￥{{scope.row.caseUnitPrice}}
						</template>
					</el-table-column>
					<el-table-column label="提成系数" align="center" prop="commission" />
					<el-table-column label="启用状态" align="center" prop="status">
						<template v-slot="scope">
							<el-switch v-model="scope.row.status" class="ml-2" inline-prompt active-text="启用"
								inactive-text="禁用" @click="updateGoods(scope.row)" :loading="loading" />
						</template>
					</el-table-column>
					<el-table-column label="关联产品" align="center" prop="productName" width="150" />
					<el-table-column label="最小单位" align="center" prop="minUnit" />
					<el-table-column label="整件数量" align="center" prop="caseQuantity" />
					<el-table-column label="销售渠道" align="center" prop="salesChannel">
						<template v-slot="scope">
							<dict-tag :options="bus_channel" :value="scope.row.channelType" />
						</template>
					</el-table-column>
					
					<el-table-column label="更新时间" align="center" prop="updateTime" width="200" />

					<el-table-column fixed="right" label="操作" align="center" width="200">
						<template v-slot="scope">
							<el-button size="mini" type="text" @click="handleDetail(scope.row)"
							v-hasPermi="['goodsDetail:detail']"
							>查看详情</el-button>
							<el-button size="mini" type="text" @click="handleUpdate(scope.row)"
								v-hasPermi="['commodity:edit']">编辑</el-button>
							<el-button size="mini" type="text" @click="handleDelete(scope.row)"
								v-hasPermi="['commodity:remove']">删除</el-button>
						</template>
					</el-table-column>
				</el-table>

				<pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
					v-model:limit="queryParams.pageSize" @pagination="getList" />
			</div>
		</div>
		<!-- 编辑/新增分类树弹窗 -->
		<el-dialog :title="title" center v-model="treeFormOpen" width="385px" append-to-body>
		  <el-form ref="refTreeForm" :model="form" :rules="rules" label-width="80px">
		    <el-form-item label="名称:" prop="name">
		      <el-input
		          size="large"
		          v-model="form.name"
		          placeholder="请输入"
				  style="200px"
		      />
		    </el-form-item>
		  </el-form>
		  <div slot="footer" class="dialog-footer text-right mt30">
			  <el-button class="cancelSubBtn" @click="treeFormOpen = false">取 消</el-button>
			  <el-button type="primary" @click="treeDataSubmit" class="mainSubBtn">确 定</el-button>
		  </div>
		</el-dialog>
		<!-- 商品弹窗 -->
		<operateGoods ref="goodsPop" @refreshList="getList"></operateGoods>
	</div>
</template>

<script setup name="ProductSetup">
	import {
		listClassify1, //商品分类树
		addTree1,//商品分类树新增
		delTree1,//商品分类树删除
		listGoods,//列表
		updateGoodsStatus,//列表启用禁用
		delGoods
	} from "@/api/business/product";
	import {
		Search
	} from '@element-plus/icons-vue'

	const {
		proxy
	} = getCurrentInstance();
	const {
		bus_channel,//销售渠道
		bus_toxicity,
		bus_sosage_form,
		bus_product_category,
		bus_active_ingredient_content
	} = proxy.useDict(
		"bus_channel",
		"bus_toxicity", "bus_sosage_form", "bus_product_category", "bus_active_ingredient_content");
</script>
<script>
	import operateGoods from "./components/operateGoods.vue";
	export default {
		components:{
			operateGoods
		},
		data() {
			return {
				showCate:true,
				loading: true, // 遮罩层
				ids: [], // 选中数组
				single: true, // 非单个禁用
				multiple: true, // 非多个禁用
				showSearch: true, //显示搜索条件
				total: 0, // 总条数
				list: [], // 产品表格数据
				title: '', // 弹出层标题
				open: false, // 是否显示弹出层
				queryParams: {
					pageNum: 1,
					pageSize: 10,
					keyword: null, // 产品名称 品牌名称 产品编码
					classifyId:'',
					channelType: null, // 销售渠道
				}, //查询参数
				data: [],//分类树数据
				title: '新增', // 弹出层标题
				treeFormOpen:false,//新增弹窗
				rules: {
				  name: [{required: true, message: "请输入类别名称", trigger: "blur"}],
				},
				form:{
					name:'',
					parentId:'',//父id
					ancestors:'',//id链
					level:'',//层级
					id:''
				},
				classifyArr:[],//分类
			}
		},
		created() {
			this.getTree(1)
		},
		methods: {
			handleNodeClick(e){
				if(e.id*1 != -1){
					this.queryParams.classifyId = e.id	
			    }else{
					this.queryParams.classifyId = ''
				}				
				this.getList();
			},
			resetAdd(){
				this.reset()
				this.treeFormOpen = true
			},
			reset(){
				this.form = {
					name:'',
					parentId:'',//父id
					ancestors:'',//id链
					level:'',//层级
					id:''
				}
			},
			append(node,data) {
				console.log(node,'level')
				this.reset()
				this.treeFormOpen = true
				if(node.data.id*1 != -1){
					this.form.parentId = node.data.id
				}
				this.form.ancestors = node.data.ancestors
				this.form.level = node.level
			},
			// 编辑
			edit(node,data){
				this.title = '编辑'
				this.reset()
				this.treeFormOpen = true
				this.form.parentId = node.data.parentId
				this.form.ancestors = node.data.ancestors
				this.form.name = node.data.name
				this.form.id = node.data.id
				this.form.level = node.level
			},
			remove(node, data) {
				console.log(node,'node')
				let that = this
				this.$modal
				  .confirm('是否确认删除"' + node.data.label + '"的数据项？')
				  .then(function () {
				    delTree1(node.data.id).then(res=>{
						if(res.code == 200){
							that.getTree()
							this.$modal.msgSuccess("删除成功");
						}
					})
				  })
				  .catch(() => { });
				
			},
			//分类树
			getTree(num) {
				listClassify1().then(res => {
					if (res.code == 200) {
						let arr = [{
							ancestors:'',
							id:'-1',
							name:'全部',
							parentId:''
						}]
						let dataArr = arr.concat(res.data)
						for (let key in dataArr) {
							dataArr[key].label = dataArr[key].name
						}
						this.classifyArr = dataArr
						this.data = this.handleTree(dataArr)
						if(num == 1){
							this.getList()
						}
					}
				})
			},
			// 分类树新增
			treeDataSubmit(){
				console.log(this.form,'form')
				addTree1(this.form).then(res=>{
					if(res.code == 200){
						this.treeFormOpen = false
						this.getTree()
					}
				})
			},
			//查询商品列表
			getList() {
				this.loading = true;
				listGoods(this.queryParams).then((response) => {
					this.list = response.rows;
					for(let key in this.list){
						this.list[key].status = this.list[key].status == '0' ? true : false
						for(let j in this.classifyArr){
							if(this.list[key].classifyId == this.classifyArr[j].id){
								this.list[key].classifyName = this.classifyArr[j].name
							}
						}
					}
					this.total = response.total;
					this.loading = false;
				});
			},
			// 启用禁用
			updateGoods(row){
				this.loading = true;
				let item = {
					id: row.id,
					status: row.status == true ? 0 : 1,
				}
				updateGoodsStatus(item).then(res=>{
					if(res.code == 200){
						this.$modal.msgSuccess("启用状态更新成功");
						this.loading = false;
						this.getList();
					}
				})
			},
			/** 搜索按钮操作 */
			handleQuery() {
				this.queryParams.pageNum = 1;
				this.getList();
			},
			/** 重置按钮操作 */
			resetQuery() {
				this.resetForm("queryForm");
				this.handleQuery();
			},
			// 启用状态操作
			updateEnabled(row) {
				this.loading = true;
				let item = {
					id: row.id,
					status: row.status,
				}
				updateProduct(item).then((response) => {
					this.$modal.msgSuccess("启用状态更新成功");
					this.loading = false;
					this.getList();
				});
			},
			//新增
			handleAdd(){
				this.$refs.goodsPop.open('')
				// this.$router.push('/goods/goodsOperate')
			},
			// 编辑
			handleUpdate(row){
				this.$refs.goodsPop.open(row.id)
				// this.$router.push('/goods/goodsOperate?id='+row.id)
			},
			// 查看详情
			handleDetail(row){
				this.$refs.goodsPop.open(row.id,1)
				// this.$router.push('/goods/goodsDetail?id=' + row.id)
			},
			// 多选框选中数据
			handleSelectionChange(selection) {
				this.ids = selection.map((item) => item.id);
				this.single = selection.length !== 1;
				this.multiple = !selection.length;
			},
			handleDelete(row){
			  const ids = row.id || this.ids;
			  let that = this
			  this.$modal
			    .confirm('是否确认删除商品编号为"' + ids + '"的数据项？')
			    .then(function () {
			      delGoods(ids).then(res=>{
					  that.getList()
					  this.$modal.msgSuccess("删除成功");
				  })
			    })
			    .catch(() => { });
			}
		}
	}
</script>
<style>
	.custom-tree-node{
		flex: 1;
	}
	.el-tree-node{
		margin: 6px 0;
	}
	.width1{
		width: calc(100% - 300px);
	}
	.width2{
		width: 100%;
	}
</style>